<template>
 <div class="card-table">
    <div class="header">
        <div @click="goBack" class="goBackIcon">
            <i class="el-icon-arrow-left" style="margin-right:1px;"></i>返回
        </div>
        <div style="margin-left:16px;"><span v-if="jumpType === 'showByorders'">工单详情</span>
          <span v-else>工单质检</span>
          <div class="greyText">
            ( {{this.mes.createTime}}&nbsp;&nbsp;&nbsp;{{this.mes.productType}}&nbsp;&nbsp;{{this.mes.diameterSpecification}}&nbsp;&nbsp;{{this.mes.specification}} )
          </div>
        </div>
    </div>
    <div class="main">
      <div class="topSearch card-search">
        <el-form :inline="true" :model="formInline" key="1" class="demo-form-inline">
          <el-form-item label="石墨棒编号">
            <el-input size="small" v-model="formInline.name"></el-input>
          </el-form-item>
          <el-form-item label="产品状态">
            <el-select size="small" v-model="formInline.productStatus">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="formInline.productStatus === '已质检'" label="正废品">
            <el-select size="small" v-model="formInline.positiveWaste" clearable>
              <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button  type="primary" @click="getQualityData">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="tableclass">
        <tableQuality :tabledata="this.TABLEdata" :needEdit="editing">
          <el-table-column
            slot="status"
            label="产品状态"
            align="center">
            <template slot-scope="scope">
              <el-tag size="medium" :type="scope.row.productStatus === '已质检' ? 'success' : 'danger'">{{scope.row.productStatus}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            slot="checkMans"
            label="工单质检人"
            width="120"
            align="center">
            <template slot-scope="scope">
              <div>{{scope.row.checkMan}}</div>
            </template>
          </el-table-column>
          <el-table-column
            slot="operation"
            label="操作"
            align="center"
            v-if="jumpType !== 'showByorders'"
            width="150">
            <template slot-scope="scope">
              <div class="btns" style="display: flex; margin-left: 20px">
                <el-button v-if="!scope.row.saveOrEdit" :disabled="scope.row.saveOrEdit" class="btnStyle" type="primary" @click="editRow(scope.row)">编辑</el-button>
                <el-button v-else class="btnStyle" type="danger" @click="cancels(scope.row)">取消</el-button>
                <el-button :disabled="!scope.row.saveOrEdit" class="btnStyle" type="success" @click="saveForm(scope.row)">保存</el-button>
              </div>
            </template>
          </el-table-column>
        </tableQuality>
        <div
          class="block"
          style="display: flex; flex-direction: row-reverse; margin-top: 10px; padding-right: 10px"
        >
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currPage"
            :page-sizes="[10, 20, 30]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
 </div>
</template>

<script>
import { profileQualityDataByOrder, profileQualityUpdate } from '@/api/profileApi/profileOrder.js'
import tableQuality from '@/components/tableQuality/index.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'qualityItem',
  components: {
    tableQuality
  },
  data () {
    return {
      orderId: '',
      mes: null,
      jumpType: '',
      TABLEdata: {
        formHead: [],
        tableAllData: []
      },
      formInline: {
        name: '',
        productStatus: '全部',
        positiveWaste: ''
      },
      options: [
        {
          label: '待质检',
          value: '待质检'
        },
        {
          label: '已质检',
          value: '已质检'
        },
        {
          label: '全部',
          value: '全部'
        }
      ], // 调获取规格类型接口
      options2: [
        {
          value: '正品',
          label: '正品'
        },
        {
          value: '废品',
          label: '废品'
        }
      ],
      ruleForm: {},
      saveOrEdit: false,
      pageSize: 10,
      currPage: 1,
      total: 50,
      editGroup: [],
      editing: [],
      itemForm: null
    }
  },
  computed: {
    ...mapGetters({
      getUserInfos: 'getUserInfo'
    })
  },
  created () {
    this.orderId = this.$route.query.orderId
    this.jumpType = this.$route.query.type // checkByorders showByorders
    this.mes = JSON.parse(this.$route.query.mes)
    console.log(this.$route.query.type) // 刷新也在
    this.getQualityData()
  },
  mounted () {
  },
  methods: {
    goBack () {
      if (this.editing.length > 0) {
        this.$message({
          message: '有编辑好的没有保存',
          type: 'warning'
        })
      } else {
        this.$router.go(-1)
      }
    },
    getQualityData () {
      const params = {
        rodNumber: this.formInline.name,
        productStatus: this.formInline.productStatus, // 产品状态
        isCertified: this.formInline.productStatus === '已质检' ? this.formInline.positiveWaste : '',
        pageSize: this.pageSize,
        orderNumber: this.orderId,
        // status: '成型',
        currPage: this.currPage
      }
      console.log('paramsparams', params)
      profileQualityDataByOrder(params).then(res => {
        if (res.data.code === 200) {
          console.log('成型质检', res.data.data)
          if (res.data.data !== null) {
            var oneLevel = JSON.parse(JSON.stringify(res.data.data.formHead))
            if (res.data.data.data[0].productType !== '方子') {
            // delete oneLevel.square
              oneLevel.diameter = '直径/mm'
              oneLevel.height = '高度/mm'
            // delete oneLevel.circularColumn
            } else {
            // delete oneLevel.circularColumn
              oneLevel.length = '长度/mm'
              oneLevel.width = '宽度/mm'
              oneLevel.heightSquare = '高度/mm'
            // delete oneLevel.square
            }
            var arr = []
            for (var i in oneLevel) {
              var o = {}
              o[i] = oneLevel[i]
              arr.push(o)
            }
            // console.log('arrarr', arr)
            if (this.editing.length !== 0) {
              this.editing.forEach((item) => { // 将还有没编辑的还原状态
                res.data.data.data.forEach(i => {
                  if (item.rows === i._id) {
                    i.saveOrEdit = true
                  }
                })
              })
            }
            this.TABLEdata.tableAllData = res.data.data.data
            this.total = res.data.data.totalCount
            this.TABLEdata.formHead = arr
          } else {
            this.TABLEdata.tableAllData = res.data.data
            this.$message({
              message: '数据为空',
              type: 'warning'
            })
          }
        }
      })
    },
    editRow (row) {
      console.log('点击编辑', row)
      row.hightLight = true
      if (row.isCertified === '废品') {
        row.isdisabled = true
        row.numNotNeedUpdate = true
      }
      this.ruleForm = row
      this.ruleForm.saveOrEdit = true
      this.editing.push({ // 多个要编辑
        booleanss: true,
        rows: row._id,
        rowItemPass: JSON.parse(JSON.stringify(row)) // 点击编辑的时候保存最初状态
      })
      if (row.isCertified === '废品') { // 默认填充
        row.isCertified = '废品'
      } else {
        row.isCertified = '正品'
      }
    },
    copyApart (old, news) {
      for (var k in news) {
        old[k] = news[k]
      }
    },
    cancels (row) {
      var cancelRowitem = this.editing.filter(item => { return item.rows === row._id })
      this.copyApart(row, cancelRowitem[0].rowItemPass)
      row.saveOrEdit = false
      row.hightLight = false
      this.editing.splice(this.findIndex(this.editing, row._id), 1)
    },
    // 计算 体积 密度
    computeDensityAndV (row) {
      if (row.productType !== '方子') {
        row.height = parseFloat(row.height)
        row.diameter = parseFloat(row.diameter)
        row.weight = parseFloat(row.weight)
        row.volume = Math.PI * row.height * 0.001 * (row.diameter / 2) * (row.diameter / 2)
        // row.volume = Math.floor(row.volume * 100) / 100 // 向下取整保留两位
        row.density = Math.floor(row.weight * 1000 / row.volume * 100) / 100
        row.height = row.height.toString()
        row.diameter = row.diameter.toString()
        row.weight = row.weight.toString()
        row.volume = row.volume.toString()
        row.density = row.density.toString()
      } else {
        row.heightSquare = parseFloat(row.heightSquare)
        row.weight = parseFloat(row.weight)
        row.length = parseFloat(row.length)
        row.width = parseFloat(row.width)
        row.volume = row.length * row.width * row.heightSquare
        row.density = Math.floor(row.weight * 1000 / row.volume * 100) / 100
        row.heightSquare = row.heightSquare.toString()
        row.length = row.length.toString()
        row.width = row.width.toString()
        row.weight = row.weight.toString()
        row.volume = row.volume.toString()
        row.density = row.density.toString()
      }
    },
    findIndex (arr, item) {
      for (let index = 0; index < arr.length; index++) {
        if (arr[index].rows === item) {
          return index
        }
      }
    },
    saveForm (row) {
      console.log('保存的这一行 修改这一行', row, row._id)
      if ((row.height !== '-' && row.weight !== '-' && row.diameter !== '-') || (row.heightSquare !== '-' && row.weight !== '-' && row.length !== '-' && row.width !== '-')) {
        row.numNotNeedUpdate = false
        this.computeDensityAndV(row)
        row.saveOrEdit = false
        this.editing.splice(this.findIndex(this.editing, row._id), 1)
        this.itemForm = JSON.parse(JSON.stringify(row))
        delete this.itemForm.saveOrEdit
        this.itemForm.checkMan = this.getUserInfos.account
        profileQualityUpdate(this.itemForm).then(res => {
          console.log('编辑成功没', res)
          if (res.data.code === 200) {
            row.hightLight = false
            this.getQualityData()
            this.$message({
              showClose: true,
              message: '编辑成功',
              type: 'success'
            })
          }
        })
      } else {
        if (row.numNotNeedUpdate === true) {
          // 废品状态
          row.saveOrEdit = false
          const rowCopy = JSON.parse(JSON.stringify(row))
          delete rowCopy.saveOrEdit
          delete rowCopy.numNotNeedUpdate
          rowCopy.checkMan = this.getUserInfos.account
          profileQualityUpdate(rowCopy).then(res => {
            console.log('编辑废品 不传长宽', res)
            this.editing.splice(this.findIndex(this.editing, row._id), 1)
            if (res.data.code === 200) {
              row.hightLight = false
              this.getQualityData()
              this.$message({
                showClose: true,
                message: '编辑成功',
                type: 'success'
              })
            }
          })
        } else { // 每一项包含0的情况
          row.saveOrEdit = true
          this.$message.error('每一项都需填写')
        }
      }
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getQualityData()
    },
    handleCurrentChange (val) {
      this.currPage = val
      this.getQualityData()
    }
  }
}
</script>

